/*
 * @lc app=leetcode.cn id=121 lang=csharp
 *
 * [121] 买卖股票的最佳时机
 */

// @lc code=start
public class Solution {
    public int MaxProfit(int[] prices) {
        var sellMax = -1;
        var buyMin = int.MaxValue;
        
        var sellMaxAns = -1;
        var buyMinAns = int.MaxValue;
        
        for (int i = prices.Length - 1; i >= 0; i--)
        {
            if (prices[i] > sellMax)
            {
                sellMax = prices[i];
                buyMin = int.MaxValue;
            }
            else if (prices[i] < buyMin)
            {
                buyMin = prices[i];
            }
            if (sellMax - buyMin > sellMaxAns - buyMinAns)
            {
                sellMaxAns = sellMax;
                buyMinAns = buyMin;
            }
        }
        return Math.Max(sellMaxAns - buyMinAns, 0);
    }
}
// @lc code=end

